/* Copyright 2008 Bas van den Berg
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "InstancePortal.h"
#include "MudPlayer.h"
#include "Area.h"
#include "Room.h"
#include "color.h"

using namespace std;
using namespace Chronos;


InstancePortal::InstancePortal(
			const string& arriveMsg_
			, const string& leaveMsg_
			, const string& enterMsg_)
    : arriveMsg(arriveMsg_)
    , leaveMsg(leaveMsg_)
    , enterMsg(enterMsg_)
{}


InstancePortal::~InstancePortal() {
    for (InstancesIter iter = instances.begin(); iter != instances.end(); ++iter) {
        delete iter->second;
    }
}


void InstancePortal::pass(MudPlayer& player) {
    Area* instance = findInstance(player);
    if (instance == 0) {
        instance = createInstance(player);
        player.write(ANSI_BLUE"[creating new instance]"ANSI_NORMAL"\n");
    } else {
        player.write(ANSI_BLUE"[using existing instance]"ANSI_NORMAL"\n");
    }
    // move player to instance
	Room* room = player.getRoom();
	room->removePlayer(player, leaveMsg);
    if (enterMsg != "") player.write(enterMsg);
    instance->addPlayer(player, 1, arriveMsg);
}


Area* InstancePortal::findInstance(MudPlayer& player) const {
    InstancesConstIter iter = instances.find(player.getName());
    if (iter != instances.end()) {
        return iter->second;
    }
    return 0;
}


Area* InstancePortal::createInstance(MudPlayer& player) {
    Area* area = new Area(1, "Instance Area");
    Room* centralRoom = new Room("Instance", "So this is what an instance looks like...");
    area->addRoom(1, *centralRoom);

    instances[player.getName()] = area;

    return area;
}


